package no.nordicsemi.android.nrftoolbox.viewmodel

import androidx.core.net.toUri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import no.nordicsemi.android.analytics.AppAnalytics
import no.nordicsemi.android.analytics.Link
import no.nordicsemi.android.analytics.ProfileOpenEvent
import no.nordicsemi.android.common.navigation.Navigator
import no.nordicsemi.android.nrftoolbox.ScannerDestinationId
import no.nordicsemi.android.service.profile.ServiceApi
import no.nordicsemi.android.toolbox.profile.ProfileDestinationId
import no.nordicsemi.android.toolbox.profile.repository.DeviceRepository
import no.nordicsemi.android.toolbox.profile.data.UARTSensorData
import no.nordicsemi.android.toolbox.profile.manager.repository.UartRepository
import kotlinx.coroutines.launch
import javax.inject.Inject

internal data class HomeViewState(
    val connectedDevices: Map<String, ServiceApi.DeviceData> = emptyMap(),
    val sensorDataMap: Map<String, UARTSensorData> = emptyMap(),  // 设备地址 -> 传感器数据
)

private const val GITHUB_REPO_URL = "https://github.com/NordicSemiconductor/Android-nRF-Toolbox.git"
private const val NORDIC_DEV_ZONE_URL = "https://devzone.nordicsemi.com/"

@HiltViewModel
internal class HomeViewModel @Inject constructor(
    private val navigator: Navigator,
    deviceRepository: DeviceRepository,
    private val analytics: AppAnalytics,
) : ViewModel() {
    private val _state = MutableStateFlow(HomeViewState())
    val state = _state.asStateFlow()

    init {
        // Observe connected devices from the repository
        deviceRepository.connectedDevices.onEach { devices ->
            _state.update { currentState ->
                currentState.copy(connectedDevices = devices)
            }
        }.launchIn(viewModelScope)
        
        // Observe UART sensor data for all connected devices
        observeSensorData()
    }
    
    private fun observeSensorData() {
        // 监听所有设备的传感器数据
        // 注意：这需要从UartRepository获取数据
        // 由于UartRepository是单例，我们可以在需要时访问
    }
    
    // 格式化传感器数据为显示字符串（一行两个，上下对齐）
    fun formatSensorData(sensorData: UARTSensorData?): String? {
        if (sensorData == null || !sensorData.isValid) return null
        
        return buildString {
            // 第一行：温度和心率
            append("温度: ${String.format("%.1f", sensorData.temperature)}°C  |  ")
            appendLine("心率: ${sensorData.heartRate}bpm")
            // 第二行：血氧和电量
            append("血氧: ${sensorData.bloodOxygen}%  |  ")
            append("电量: ${sensorData.battery}%")
        }
    }

    fun onClickEvent(event: UiEvent) {
        when (event) {
            UiEvent.OnConnectDeviceClick -> navigator.navigateTo(ScannerDestinationId)
            is UiEvent.OnDeviceClick -> {
                // Log the event for analytics.
                analytics.logEvent(ProfileOpenEvent(event.profile))

                navigator.navigateTo(
                    ProfileDestinationId, event.deviceAddress
                )
            }

            // 已注释掉 GitHub 点击事件
            /*
            UiEvent.OnGitHubClick -> {
                // Log the event for analytics.
                analytics.logEvent(ProfileOpenEvent(Link.GITHUB))
                navigator.open(GITHUB_REPO_URL.toUri())
            }
            */

            // 已注释掉 Nordic DevZone 点击事件
            /*
            UiEvent.OnNordicDevZoneClick -> {
                // Log the event for analytics.
                analytics.logEvent(ProfileOpenEvent(Link.DEV_ACADEMY))
                navigator.open(NORDIC_DEV_ZONE_URL.toUri())
            }
            */
        }
    }
    
    // ========== UART命令发送功能 ==========
    
    /**
     * 发送开始工作命令：FF FE 00
     */
    fun sendStartCommand(deviceAddress: String) {
        viewModelScope.launch {
            try {
                // 直接发送3字节二进制命令
                val command = byteArrayOf(0xFF.toByte(), 0xFE.toByte(), 0x00.toByte())
                UartRepository.sendBytes(deviceAddress, command)
            } catch (e: Exception) {
                // 记录错误日志
                e.printStackTrace()
            }
        }
    }
    
    /**
     * 发送停止工作命令：FF FE 01
     */
    fun sendStopCommand(deviceAddress: String) {
        viewModelScope.launch {
            try {
                val command = byteArrayOf(0xFF.toByte(), 0xFE.toByte(), 0x01.toByte())
                UartRepository.sendBytes(deviceAddress, command)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    /**
     * 发送闪烁命令：FF FE DD
     */
    fun sendBlinkCommand(deviceAddress: String) {
        viewModelScope.launch {
            try {
                val command = byteArrayOf(0xFF.toByte(), 0xFE.toByte(), 0xDD.toByte())
                UartRepository.sendBytes(deviceAddress, command)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}